<template>
  <!-- TODO:组件化 -->
  <el-form ref="form" :rules="loginRules" :model="form">
    <el-col :span="24">
      <el-form-item prop="mobile">
        <el-input
          v-model="form.mobile"
          placeholder="请输手机号"
          @wheel.native.prevent="stopScrollFun($event)"
          oninput="if(value.length > 11) value=value.slice(0, 11)"
          @keydown.native="
            (e) =>
              ((e.ctrlKey || e.metaKey) &&
                ['c', 'v', 'a', 'x'].includes(e.key.toLowerCase())) ||
              /[0-9]/.test(e.key) ||
              [
                'Backspace',
                'Tab',
                'ArrowLeft',
                'ArrowRight',
                'Enter',
                'Delete',
              ].includes(e.key) ||
              e.preventDefault()
          "
        ></el-input>
      </el-form-item>
    </el-col>
    <el-col :span="15">
      <el-form-item prop="code">
        <el-input
          v-model.trim="form.code"
          placeholder="请输入图形码"
          maxlength="4"
          @keyup.enter.native="handleSubmit"
          class="code_input"
        />
      </el-form-item>
    </el-col>
    <el-col :span="9">
      <div class="code">
        <img :src="imgPicture" alt="" @click="getPicture" />
      </div>
    </el-col>
    <el-col :span="24">
      <el-form-item prop="sms_code">
        <el-input
          ref="sms_code"
          class="sms_code_input"
          v-model.trim="form.sms_code"
          placeholder="请输入验证码"
          name="sms_code"
          auto-complete="on"
          tabindex="4"
          type="number"
          @wheel.native.prevent="stopScrollFun($event)"
          oninput="if(value.length > 6) value=value.slice(0, 6)"
          @keydown.native="
            (e) =>
              (e.returnValue = ['e', 'E', '-', '+'].includes(e.key)
                ? false
                : e.returnValue)
          "
        >
          <template slot="append">
            <div class="sendCode">
              <el-button
                @click="getPhoneMsg(1)"
                :disabled="disabledVertify"
                type="text"
              >
                {{ codeInfoText }}</el-button
              >
            </div>
          </template>
        </el-input>
      </el-form-item>
    </el-col>
    <el-col :span="24">
      <el-form-item>
        <div class="bottombuttons">
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            登录
          </el-button>
          <div class="changeFormButtons">
            <p @click="changeForm('register')" class="changeForm">注册账号</p>
            <p @click="changeForm('forget')" class="changeForm">忘记密码</p>
          </div>
        </div>
      </el-form-item>
    </el-col>
  </el-form>
</template>

<script>
import { validChinesePhoneNumber } from "@/utils/validate";
import { captchaInit, sendSms } from "@/api/user";
import { burryPointForLogin } from "@/api/data";
import axios from "axios";
import qs from "qs";
export default {
  name: "smsloginForm",
  data() {
    const validateChinesePhoneNumber = (rule, value, callback) => {
      if (!validChinesePhoneNumber(value)) {
        callback(new Error("请输入正确的手机号码"));
      }
      callback();
    };
    return {
      codeInfoText: "发送验证码",
      disabledVertify: false,
      disabledCatpchaFlash: false,
      captchaId: "",
      imgPicture: "",
      form: {
        mobile: "",
        code: "",
        sms_code: "",
      },
      loginRules: {
        mobile: [
          {
            required: true,
            trigger: "blur",
            validator: validateChinesePhoneNumber,
          },
        ],
        code: [{ required: true, trigger: "blur", message: "请输入验证码" }],
        sms_code: [
          { required: true, trigger: "blur", message: "请输入短信验证码" },
        ],
      },
      loading: false,
    };
  },
  created() {
    this.initCaptcha();
    document.title = "短信登录";
  },
  methods: {
    reqReportLoginAction() {
      const params = {
        rightId: "-2",
        cardType: localStorage.getItem("cardType"),
        description: "使用了职业大全",
        patform: 2,
        personId: "-1",
      };
      burryPointForLogin(params)
        .then((res) => {
          if (res.code == 200) {
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    changeForm(type) {
      this.$store.dispatch("user/setFormType", type);
    },
    //初始化并获取验证码
    async initCaptcha() {
      const res = await captchaInit();
      if (res.code == 200) {
        this.captchaId = res.data;
        this.imgPicture =
          process.env.VUE_APP_BACK_API +
          "api-auth/common/captcha/draw/" +
          res.data;
      } else {
        this.$message({
          type: "error",
          message: res.status_desc,
        });
      }
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          //通过验证
          this.loading = true;
          const params = {
            grant_type: "sms_code",
            mobile: this.form.mobile,
            username: this.form.mobile,
            accountType: "appClientZtSms",
            client_id: "jGKuZdBW7pAsKBNw",
            client_secret: "5e03b32605fe4d50b2d5b4e8145655dc",
            code: this.form.sms_code,
          };
          axios
            .post(
              process.env.VUE_APP_BACK_API + "api-auth/oauth/token",
              qs.stringify(params),
              {
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
              }
            )
            .then((res) => {
              if (res.data.code == 200) {
                // 登录成功处理
                this.$message.success("登录成功！");
                // 存储手机号码
                localStorage.setItem("mobile", this.form.mobile);
                // 注意两层data
                localStorage.setItem(
                  "token",
                  res.data.data.tokenHead + "" + res.data.data.token
                );
                localStorage.setItem("roleType", 10);
                localStorage.setItem("origin", 'loginPage');
                const query =
                  { ...this.$route.query, origin: "loginPage" } || {};
                this.$bus.$emit("generalReportAction", {
                  etId: 40013,
                  personId: "-1",
                  cardType: localStorage.getItem("cardType"),
                  jumpSource: 60,
                  sourceType: 60,
                });
                this.reqReportLoginAction();
                setTimeout(() => {
                  this.$router.push({ name: "position", query });
                }, 300);
              } else {
                this.$message.error(res.data.status_desc || "请重试！");
                this.getPicture();
              }
            })
            .catch((e) => {
              this.$message.error(res.data.status_desc || "请重试！");
              this.getPicture();
              console.log(e);
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    getPicture() {
      //500毫秒内最多获取一次；
      if (this.disabledCatpchaFlash) return;
      this.initCaptcha();
      this.disabledCatpchaFlash = true;
      setTimeout(() => {
        this.disabledCatpchaFlash = false;
      }, 1000);
    },
    stopScrollFun(evt) {
      evt = evt || window.event;
      if (evt.preventDefault) {
        // Firefox
        evt.preventDefault();
        evt.stopPropagation();
      } else {
        // IE
        evt.cancelBubble = true;
        evt.returnValue = false;
      }
      return false;
    }, // 获取短信验证码
    getPhoneMsg(smsType) {
      if (this.disabledVertify) return;
      if (!this.form.mobile) {
        this.$message({
          type: "error",
          message: "请输入手机号码",
        });
        return;
      }
      if (!this.form.code) {
        this.$message({
          type: "error",
          message: "请输入验证码",
        });
        return;
      }
      sendSms({
        mobile: this.form.mobile,
        smsType, //0注册验证码  1登录验证码  2找回密码验证码
        code: this.form.code,
        captchaId: this.captchaId,
      }).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "发送验证码成功",
            duration: 3000,
          });
          this.disabledVertify = true;
          if (this.codeInfoText == "发送验证码") {
            let s = 180;
            this.codeInfoText = s + "s";
            let timer = setInterval(() => {
              s -= 1;
              this.codeInfoText = s + "s";
              if (s == 0) {
                this.codeInfoText = "发送验证码";
                this.disabledVertify = false;
                clearInterval(timer);
              }
            }, 1000);
          }
        } else {
          this.$message({
            type: "error",
            message: res.status_desc,
          });
          this.initCaptcha();
        }
      });
    },
  },
};
</script>

<style lang="scss"></style>

<style lang="scss" scoped>
.login-form {
  width: 368px;
  padding: 32px;
  background: #ffffff;
  border-radius: 4px;
  .form-info {
    .logo {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 39px;
      img {
        width: 154px;
        height: 45px;
      }
    }
    .desc {
      width: 80px;
      height: 26px;
      font-family: MicrosoftYaHei, MicrosoftYaHei;
      font-weight: bold;
      font-size: 20px;
      color: #222222;
      line-height: 26px;
      text-align: left;
      font-style: normal;
      margin-bottom: 31px;
    }
  }
  .code {
    display: flex;
    align-items: center;
    z-index: 10;
    height: 40px;
    cursor: pointer;
    img {
      max-width: 100%;
      height: 40px;
    }
  }
  ::v-deep .el-input-group__append {
    border-radius: 2px;
    background: #f4f6fa;
    border: 1px solid #e3e8ef;
    padding: 0;
  }
  .sendCode {
    display: flex;
    justify-content: center;
    width: 100px;
    color: #0b6eff;
  }
  .bottombuttons {
    ::v-deep .el-button {
      width: 100%;
      height: 32px;
      padding-top: 7px;
      padding-bottom: 7px;
    }
    .changeFormButtons {
      display: flex;
      justify-content: center;
      .changeForm {
        text-align: center;
        cursor: pointer;
        font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
          Microsoft YaHei, Arial, sans-serif;
        font-size: 14px;
        color: #666666;
        line-height: 19px;
        font-style: normal;
        margin: 10px 0 0 0;
        padding: 0 10px;
      }
    }
  }
}
::v-deep .el-form-item {
  margin-bottom: 20px;
}
::v-deep .el-input__inner {
  width: 100%;
  height: 40px;
  background: #f4f6fa;
  border-radius: 3px;
  border: 1px solid #e3e8ef;
}
.sms_code_input {
  ::v-deep .el-input__inner {
    border-radius: 3px 0px 0px 3px;
  }
}
::v-deep .el-form-item.is-error .el-input__inner {
  border-color: #e3e8ef;
}
::v-deep .el-form-item__error {
  font-size: 12px;
  color: #e85e41;
  line-height: 16px;
  text-align: left;
  font-style: normal;
  padding-top: 0px;
  padding-left: 12px;
}
.code_input {
  ::v-deep .el-input__inner {
    border-radius: 3px 0px 0px 3px;
  }
}

.sms_code_input {
  ::v-deep .el-input__inner {
    border-right: 0;
    border-radius: 3px 0px 0px 3px;
  }
  ::v-deep .el-input-group__append {
    border-radius: 2px;
    background: #f4f6fa;
    border: 1px solid #e3e8ef;
    border-left: 0;
    padding: 0;
    width: 94px;
  }
  ::v-deep .el-input-group__append,
  .el-input-group__prepend {
    padding: 0;
  }
  .sendCode {
    ::v-deep.el-button {
      span {
        padding: 0 12px;
        border-left: 1px solid #e3e8ef;
      }
    }
  }
}
//删除number的箭头
::v-deep.login-container input::-webkit-outer-spin-button,
::v-deep.login-container input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
::v-deep.login-container input[type="number"] {
  -moz-appearance: textfield;
}
::v-deep.el-input .el-input__inner {
  line-height: 1px !important;
}

@media (max-width: 1440px) {
  .login-block {
    top: 120px !important;
  }
}
</style>
